/*
 * @Author: xiaosihan
 * @Date: 2021-05-23 16:20:41
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2021-07-25 02:11:03
 */

import THREEInstancedMesh, { THREEInstancedMeshItem } from "../InstancedMesh/THREEInstancedMesh";
import Object3D from "../Object3D/Object3D";
import Object3DComponent, { Object3DComponentProps } from "../Object3D/Object3DComponent";


export interface RaycasterMeshProps extends Object3DComponentProps {
    /**
     * 碰撞模型的类型 
     * @cube 立方体
     * @cylinder 圆柱
     * @plane 面
     */
    type?: "cube" | "cylinder" | "plane"
}

interface State { }

export default class RaycasterMesh extends Object3DComponent<RaycasterMeshProps, State> {

    constructor(props: RaycasterMeshProps) {
        super(props);
        // 创建基础对象object3d;
        let name = this.getConstructorName();

        this.object3d = new (Function("THREEInstancedMeshItem", `
            return class ${name} extends THREEInstancedMeshItem {};
        `)(THREEInstancedMeshItem));

    }

    declare object3d: Object3D & THREEInstancedMeshItem;

    static defaultProps = {
        type: "cube"
    }

    // 添加实例模型成员
    addItemToInstanceMesh() {
        const { type } = this.props;
        const { collideCubeInstanceMesh, collideCylindricalInstanceMesh, collidePlaneInstanceMesh } = this.context;

        if (type === "cube") {
            (collideCubeInstanceMesh as THREEInstancedMesh).addItem(this.object3d);
        } else if (type === "cylinder") {
            (collideCylindricalInstanceMesh as THREEInstancedMesh).addItem(this.object3d);
        } else if (type === "plane") {
            (collidePlaneInstanceMesh as THREEInstancedMesh).addItem(this.object3d);
        }
    }

    // 移除实例模型成员
    removeItemInInstance() {
        const { collideCubeInstanceMesh, collideCylindricalInstanceMesh, collidePlaneInstanceMesh } = this.context;
        (collideCubeInstanceMesh as THREEInstancedMesh).removeItem(this.object3d);
        (collideCylindricalInstanceMesh as THREEInstancedMesh).removeItem(this.object3d);
        (collidePlaneInstanceMesh as THREEInstancedMesh).removeItem(this.object3d);
    }

    componentDidMount() {
        this.addItemToInstanceMesh();
    }

    componentDidUpdate() {
        this.removeItemInInstance();
        this.addItemToInstanceMesh();
    }

    componentWillUnmount() {
        this.removeItemInInstance();
    }

}